<template>
  <div class="data-export">
    <el-alert
      title="数据导出功能"
      type="info"
      description="导出系统数据为JSON或Excel格式，可用于备份或迁移到其他系统。"
      show-icon
      :closable="false"
      style="margin-bottom: 20px;"
    />
    
    <el-form :model="exportForm" label-width="120px">
      <el-form-item label="选择数据类型">
        <el-checkbox-group v-model="exportForm.dataTypes" @change="handleDataTypeChange">
          <el-checkbox label="products">商品数据</el-checkbox>
          <el-checkbox label="categories">分类数据</el-checkbox>
          <el-checkbox label="orders">订单数据</el-checkbox>
          <el-checkbox label="users">用户数据</el-checkbox>
          <el-checkbox label="promotions">促销数据</el-checkbox>
          <el-checkbox label="payments">支付记录</el-checkbox>
          <el-checkbox label="orderItems">订单项目</el-checkbox>
          <el-checkbox label="channels">渠道信息</el-checkbox>
          <el-checkbox label="productPrices">商品价格</el-checkbox>
          <el-checkbox label="departments">部门信息</el-checkbox>
          <el-checkbox label="roles">角色信息</el-checkbox>
          <el-checkbox label="permissions">权限数据</el-checkbox>
          <el-checkbox label="paymentMethods">支付方式</el-checkbox>
          <el-checkbox label="all" @change="handleAllChange">全部数据</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item label="导出格式">
        <el-radio-group v-model="exportForm.format">
          <el-radio label="json">JSON</el-radio>
          <el-radio label="excel">Excel</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="时间范围" v-if="showDateRange">
        <el-date-picker
          v-model="exportForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleExport" :loading="exporting">
          导出数据
        </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    
    <div v-if="exportHistory.length > 0" class="export-history">
      <h3>导出历史</h3>
      <el-table :data="exportHistory" style="width: 100%">
        <el-table-column prop="date" label="导出时间" width="180" />
        <el-table-column prop="types" label="数据类型" />
        <el-table-column prop="format" label="格式" width="100" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="downloadExport(scope.row)">
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { exportData, getExportHistory, downloadExportFile } from '@/api/migration'

export default {
  name: 'DataExport',
  data() {
    return {
      exportForm: {
        dataTypes: ['products', 'categories'],
        format: 'json',
        dateRange: null
      },
      exporting: false,
      exportHistory: [],
      // 添加所有数据类型的列表，不包括"all"
      allDataTypes: [
        'products', 'categories', 'orders', 'users', 'promotions', 
        'payments', 'orderItems', 'channels', 'productPrices', 
        'departments', 'roles', 'permissions', 'paymentMethods'
      ],
      allSelected: false
    }
  },
  computed: {
    showDateRange() {
      return this.exportForm.dataTypes.includes('orders')
    }
  },
  watch: {
    'exportForm.dataTypes': {
      handler(newValue) {
        const hasAll = newValue.includes('all');
        
        // 如果选中了"all"但没有全选
        if (hasAll && !this.allSelected) {
          // 选择所有选项
          this.selectAll();
        } 
        // 如果取消了"all"但之前是全选状态
        else if (!hasAll && this.allSelected) {
          this.allSelected = false;
        }
        // 如果所有常规选项都被手动取消，也要取消"all"
        else if (this.allSelected && !this.allDataTypes.every(type => newValue.includes(type))) {
          this.allSelected = false;
          const index = this.exportForm.dataTypes.indexOf('all');
          if (index > -1) {
            this.exportForm.dataTypes.splice(index, 1);
          }
        }
      },
      deep: true
    }
  },
  created() {
    this.fetchExportHistory()
  },
  methods: {
    // 选中所有选项的方法
    selectAll() {
      this.exportForm.dataTypes = ['all', ...this.allDataTypes];
      this.allSelected = true;
    },

    async fetchExportHistory() {
      try {
        // 实际项目中应该调用API获取历史记录
        // const { data } = await getExportHistory()
        // this.exportHistory = data
        
        // 使用模拟数据
        this.exportHistory = [
          {
            id: 1,
            date: '2023-05-31 10:30:45',
            types: '商品、分类',
            format: 'JSON',
            url: '#'
          },
          {
            id: 2,
            date: '2023-05-30 15:22:10',
            types: '订单、用户',
            format: 'Excel',
            url: '#'
          }
        ]
      } catch (error) {
        console.error('获取导出历史失败:', error)
        this.$message.error('获取导出历史失败')
      }
    },
    
    async handleExport() {
      if (this.exportForm.dataTypes.length === 0) {
        this.$message.warning('请至少选择一种数据类型')
        return
      }
      
      this.exporting = true
      
      try {
        // 实际项目中应该调用后端API进行导出
        // const response = await exportData(this.exportForm)
        
        // 模拟导出过程
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        this.$message.success('数据导出成功')
        
        // 添加到导出历史
        const now = new Date()
        const dateStr = now.toLocaleString()
        const typesStr = this.getDataTypeNames().join('、')
        
        this.exportHistory.unshift({
          id: Date.now(),
          date: dateStr,
          types: typesStr,
          format: this.exportForm.format.toUpperCase(),
          url: '#'
        })
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败，请重试')
      } finally {
        this.exporting = false
      }
    },
    
    resetForm() {
      this.exportForm = {
        dataTypes: ['products', 'categories'],
        format: 'json',
        dateRange: null
      }
      this.allSelected = false;
    },
    
    async downloadExport(row) {
      try {
        // 实际项目中应该调用API下载文件
        // const response = await downloadExportFile(row.id)
        // const blob = new Blob([response.data])
        // const link = document.createElement('a')
        // link.href = URL.createObjectURL(blob)
        // link.download = `export_${row.date.replace(/[: ]/g, '_')}.${row.format.toLowerCase()}`
        // link.click()
        // URL.revokeObjectURL(link.href)
        
        // 模拟下载过程
        this.$message.success(`正在下载 ${row.date} 的导出文件`)
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('下载失败，请重试')
      }
    },
    
    getDataTypeNames() {
      const typeMap = {
        products: '商品数据',
        categories: '分类数据',
        orders: '订单数据',
        users: '用户数据',
        promotions: '促销数据',
        payments: '支付记录',
        orderItems: '订单项目',
        channels: '渠道信息',
        productPrices: '商品价格',
        departments: '部门信息',
        roles: '角色信息',
        permissions: '权限数据',
        paymentMethods: '支付方式'
      }
      
      return this.exportForm.dataTypes.map(type => typeMap[type] || type)
    },
    
    handleDataTypeChange(value) {
      // 当选项列表变化时的处理逻辑
      const hasAll = value.includes('all');
      
      // 检查是否所有常规选项都被选中了
      const allRegularSelected = this.allDataTypes.every(type => value.includes(type));
      
      if (hasAll && !allRegularSelected) {
        // 如果选中了"all"但并非所有常规选项都选中，则选择所有选项
        this.selectAll();
      } else if (!hasAll && allRegularSelected) {
        // 如果所有常规选项都被选中，但"all"没有被选中，则添加"all"
        this.exportForm.dataTypes.push('all');
        this.allSelected = true;
      } else if (hasAll && value.length === 1) {
        // 如果只选中了"all"，则全选
        this.selectAll();
      }
    },
    
    handleAllChange(checked) {
      if (checked) {
        // 选中"all"时，选中所有选项
        this.selectAll();
      } else {
        // 取消"all"时，取消所有选项
        this.exportForm.dataTypes = [];
        this.allSelected = false;
      }
    }
  }
}
</script>

<style scoped>
.data-export {
  padding: 10px 0;
}

.export-history {
  margin-top: 30px;
  border-top: 1px solid #ebeef5;
  padding-top: 20px;
}

.export-history h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 500;
}
</style> 